package com.app.utils;

import java.io.File;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ListView;

import com.app.application.MyApplication;
import com.app.config.AppConfig;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.HttpRequest;
import com.core.lib.utils.CallBack;
import com.core.lib.utils.DeviceUtil;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.FileUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.StringUtilBase;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.utils.secure.EncodeMD5;
import com.core.lib.widget.MyDialog;
import com.lepu.app.fun.bbs.BbsDetailActivity;
import com.lepu.app.fun.index.activity.IndexKnowDetailActivity;
import com.lepu.app.fun.lottery.AppLotteryActivity;
import com.lepu.app.fun.my.MyArticleInfoActivity;
import com.lepu.app.fun.my.MyConsultActivity;
import com.lepu.app.fun.my.MyLectureDetailActivity;
import com.lepu.app.main.activity.AppBroswerActivity;
import com.lepu.pasm.R;

public class Utils {

    /*
     * 程序安装第一次启动后，删除sd卡根目录文件
     */
    public static void cleanAllFile(final Context context) {
        new Thread(new Runnable() {

            @Override
            public void run() {

                try {
                    LogUtilBase.LogD(null, "clean all file");

                    String filePath = SdLocal.getLepuRootPathSD(context);
                    LogUtilBase.LogD(null, "clean all file filePath=" + filePath);
                    if (!StringUtilBase.stringIsEmpty(filePath)) {
                        File file = new File(filePath);
                        LogUtilBase.LogD(null,
                                "clean all file state" + file.exists());
                        if (file.exists()) {
                            FileUtilBase.deleteFile(file);
                            LogUtilBase.LogD(null, "clean all file success");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    public static void cleanFile(final Context context, final String filePath,
                                 final CallBack callBack) {
        new Thread(new Runnable() {

            @Override
            public void run() {

                try {
                    if (!StringUtilBase.stringIsEmpty(filePath)) {
                        File file = new File(filePath);
                        if (file.exists()) {
                            FileUtilBase.deleteFile(file);
                            LogUtilBase.LogD(null, "clean all file");
                            if (callBack != null) {
                                callBack.callBackSuccess(null);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    public static void cleanAllCache(final Context context,
                                     final CallBack callBack) {
        new Thread(new Runnable() {

            @Override
            public void run() {

//				String tempFilePath = SdLocal.getTempFolder(context);
//				if (!StringUtilBase.stringIsEmpty(tempFilePath)) {
//					File tempFile = new File(tempFilePath);
//					if (tempFile.exists()) {
//						FileUtilBase.deleteFile(tempFile);
//						LogUtilBase.LogD(null, "clean tempFile file");
//					}
//				}

                try {
                    //image loader cache
                    UniversalImageLoadTool.clearAllCache();

                    //xutil通用缓存图像
                    BitmapLoadUtil.clearAllCache();

                    //清理头像缓存
                    HeadIconLoadUtil.clearAllCache();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (callBack != null) {
                    callBack.callBackSuccess(null);
                }
            }
        }).start();
    }

    /**
     * 定时清理缓存cache
     */
    public static void cleanByTime(Context context) {
        try {
            long start = System.currentTimeMillis();
            int lastCleanTime = AppConfig.getConfigInt(context, Const.CONFIG_APP_LAST_CLEAN_TIME, 0);//
            int currentTime = (int) (System.currentTimeMillis() / 1000);

            if (lastCleanTime <= 0) { //第一次运行

            } else {
                if ((currentTime - lastCleanTime) > Const.CLEAN_HISTORY_CACHE) {
                    //清除过期的缓存文件
                    cleanAllCache(context, null);
                }
            }
            AppConfig.setConfig(context, Const.CONFIG_APP_LAST_CLEAN_TIME, currentTime);

            LogUtilBase.LogD(null, "clean: " + (System.currentTimeMillis() - start));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * 字符串需要是 yyyy-MM-dd
     */
    @SuppressWarnings("unused")
    private static int[] getCacuteTimeDayString(String birthdayString,
                                                String dateString) {
        Date birthday = DateUtilBase.dateFromString(birthdayString,
                DateUtilBase.YEAR_MONTH_DAY);

        Date date = DateUtilBase.dateFromString(dateString,
                DateUtilBase.YEAR_MONTH_DAY);
        long time = date.getTime() - birthday.getTime();
        int day = (int) (time / 1000 / 60 / 60 / 24);

        int sui = day / 365;
        int tian = day % 365;

        if (sui < 0) {
            sui = 0;
        }

        if (tian < 0) {
            tian = 0;
        }

        int[] array = new int[]{sui, tian};

        return array;
    }

    /*
     * 特殊时间点推送
     */
    public static boolean getUserPush() {
        boolean flag = false;

        return flag;
    }

    public static String getBabyString(String birthday) {
        String result = "";

        Date birthDate = DateUtilBase.dateFromString(birthday,
                DateUtilBase.YEAR_MONTH_DAY);
        String dayString = DateUtilBase.stringFromDate(new Date(),
                DateUtilBase.YEAR_MONTH_DAY);
        Date currentDate = DateUtilBase.dateFromString(dayString,
                DateUtilBase.YEAR_MONTH_DAY);

        long time = currentDate.getTime() - birthDate.getTime();
        if (time > 0) {
            int day = (int) (time / 1000 / 60 / 60 / 24);

            if (day >= 30) {
                int sui = day / 365;

                StringBuilder sb = new StringBuilder();
                sb.append("(宝宝");

                if (sui > 0) {
                    sb.append(String.format("%d岁", sui));
                    int month = (day - 365) / 30;
                    if (month > 0) {
                        sb.append(String.format("%d个月", month));
                    }
                } else {
                    int month = day / 30;
                    if (month > 0) {
                        sb.append(String.format("%d个月", month));
                    }
                }

                sb.append(")");

                result = sb.toString();
            }
        }

        return result;
    }

    /**
     * 计算两个日期相差多少天
     *
     * @param startTime
     * @param endTime
     * @param format
     * @return
     */
    @SuppressWarnings("unused")
    @SuppressLint("SimpleDateFormat")
    public static long TimeDifference(String startTime, String endTime,
                                      String format) {
        // 按照传入的格式生成一个simpledateformate对象

        SimpleDateFormat sd = new SimpleDateFormat(format);
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        long ns = 1000;// 一秒钟的毫秒数
        long diff = 0;
        long day = 0;
        try {
            // 获得两个时间的毫秒时间差异
            diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
            day = diff / nd;// 计算差多少天
            long hour = diff % nd / nh;// 计算差多少小时
            long min = diff % nd % nh / nm;// 计算差多少分钟
            long sec = diff % nd % nh % nm / ns;// 计算差多少秒

            return day;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return day;
    }

    public static void callPhone(final Activity context, final String phone) {
        // if (readSIMCard()) { //没有SIM卡
        // UIHelper.showToast(context, "该设备，未安装sim卡");
        // return;
        // }
        MyDialog myDialog = new MyDialog(context);
        myDialog.setTitle("拨打电话").setMessage(phone)
                .setNegativeButton(R.string.cancel, null)
                .setPositiveButton(R.string.app_ok, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Uri uri = Uri.parse("tel:" + phone);
                        Intent intentCallPhone = new Intent(Intent.ACTION_DIAL,
                                uri);
                        context.startActivity(intentCallPhone);

                    }
                }).create(null).show();
    }

    public static boolean readSIMCard() {
        TelephonyManager tm = (TelephonyManager) MyApplication.getInstance()
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT) {
            return true; // 无卡
        }
        return false;// 正常

    }

    /**
     * MD5(LoginID+"LepuApp")
     *
     * @param LoginID
     * @return
     */
    public static String getCodeValue(String LoginID) {
        String value = "";

        if (!TextUtils.isEmpty(LoginID)) {
            String temp = LoginID + "LepuApp";
            value = EncodeMD5.getMd5(temp);
        }

        return value;
    }

    /**
     * 轮播图 推送 各种类型，跳转
     *
     * @param baseFragmentActivity
     * @param type
     * @param LinkTargetUrl
     * @param LinkTargetID
     */
    public static void jumpFocusPushClick(
            BaseFragmentActivity baseFragmentActivity, boolean isPush, int type, String ArticleID,
            String LinkTargetUrl, String LinkTargetID, String viewCount, String favourCount,
            String Cover, String Description) {

        switch (type) {
            case -1:// 文章详情
            case 13: //跳转到活动文章详情

                String id = "";
                if (isPush) {
                    id = LinkTargetID;
                } else {
                    id = ArticleID;
                }

                if (TextUtils.isEmpty(id)) {
                    return;
                }

                Intent intent = new Intent(baseFragmentActivity,
                        MyArticleInfoActivity.class);
                intent.putExtra("ArticleID", id);
                if (type == 13) {
                    intent.putExtra("IsHidden", true);
                }
                baseFragmentActivity.startActivity(intent, true);
                break;
            case 0:// 死图，不做跳转
                break;
            case 1:// 优酷视频 暂时对视频不做处理
                break;
            case 2: // 抽奖详情
                if (TextUtils.isEmpty(LinkTargetID)) {
                    return;
                }
                Intent lotteryIntent = new Intent(baseFragmentActivity,
                        AppLotteryActivity.class);
                lotteryIntent.putExtra("LinkTargetID", LinkTargetID);// 抽奖活动id
                lotteryIntent.putExtra("Cover", Cover);
                lotteryIntent.putExtra("Description", "");
                baseFragmentActivity.startActivity(lotteryIntent, true);
                break;
            case 3:// 专家会诊页面， 已去掉这个功能
                break;
            case 4: // 同心积分奖励页面
                if (TextUtils.isEmpty(LinkTargetUrl)) {
                    return;
                }
                MyStoreUtil.getInstance().requestMoneyMarket(baseFragmentActivity,
                        LinkTargetUrl);
                break;
            case 5:// 跳转指定链接
                if (TextUtils.isEmpty(LinkTargetUrl)) {
                    return;
                }
                Intent urlIntent = new Intent(baseFragmentActivity,
                        AppBroswerActivity.class);
                urlIntent.putExtra("url", LinkTargetUrl);
                urlIntent.putExtra("title", "");

                urlIntent.putExtra("Cover", Cover);
                urlIntent.putExtra("Description", Description);
                baseFragmentActivity.startActivity(urlIntent, true);
                break;
            case 6:// 下载同心术后天天知压缩包

                String shuId = "";
                if (isPush) {
                    shuId = LinkTargetID;
                } else {
                    shuId = ArticleID;
                }

                if (TextUtils.isEmpty(LinkTargetUrl) || TextUtils.isEmpty(shuId)) {
                    return;
                }
                Intent intentShuHouDetail = new Intent(baseFragmentActivity,
                        IndexKnowDetailActivity.class);
                intentShuHouDetail.putExtra("articleId", shuId);
                intentShuHouDetail.putExtra("url", LinkTargetUrl);
                intentShuHouDetail.putExtra("viewCount", viewCount);
                intentShuHouDetail.putExtra("favourCount", favourCount);
                baseFragmentActivity.startActivity(intentShuHouDetail, true);
                break;
            case 7:// 链接到其它文章

                if (TextUtils.isEmpty(LinkTargetID)) {
                    return;
                }

                Intent intentOther = new Intent(baseFragmentActivity,
                        MyArticleInfoActivity.class);
                intentOther.putExtra("ArticleID", LinkTargetID);
                baseFragmentActivity.startActivity(intentOther, true);
                break;
            case 8:// 链接到常见问题
                Intent intentQuestion = new Intent(baseFragmentActivity,
                        MyConsultActivity.class);
                baseFragmentActivity.startActivity(intentQuestion, true);
                break;
            case 9:// 跳转至积分商城指定页面

                UmengHelper.CustomEvent(baseFragmentActivity, UmengEvent.event_jiankangshangcheng);

                if (!TextUtils.isEmpty(LinkTargetUrl)) {
                    MyStoreUtil.getInstance().requestMoneyMarket(baseFragmentActivity, LinkTargetUrl);
                }
                break;
            case 10:// 跳转至护生堂全商城指定页面

                UmengHelper.CustomEvent(baseFragmentActivity, UmengEvent.event_jiankangshangcheng);

                if (!TextUtils.isEmpty(LinkTargetUrl)) {
                    MyStoreUtil.getInstance().requestAllMarket(baseFragmentActivity, LinkTargetUrl);
                }
                break;
            case 11://讲座详情
            case -2:
                if (TextUtils.isEmpty(LinkTargetID)) {
                    return;
                }
                Intent intentInfo = new Intent(baseFragmentActivity,
                        MyLectureDetailActivity.class);
                intentInfo.putExtra("LectureID", LinkTargetID);
                intentInfo.putExtra("Cover", Cover);
                baseFragmentActivity.startActivity(intentInfo, true);
                break;
            case 12://帖子详情
                if (TextUtils.isEmpty(LinkTargetID)) {
                    return;
                }
                Intent intentTieZiDetail = new Intent(baseFragmentActivity,
                        BbsDetailActivity.class);
                intentTieZiDetail.putExtra("threadId", LinkTargetID);
                baseFragmentActivity.startActivity(intentTieZiDetail, true);
                break;
            default:
                break;
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    /**
     *
     * @param webView
     * @param isLoadData  加载的是data true，加载的是url，false
     */
    public static void initWebViewSettings(WebView webView, boolean isLoadData) {
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(false);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setDefaultTextEncodingName("UTF -8");// 设置默认为utf-8
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setDomStorageEnabled(true);//有些网页加载出来是空白

        //========================
        if (!isLoadData) {
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
            webSettings.setUseWideViewPort(true);
            webSettings.setLoadWithOverviewMode(true);
        }

        //=========================
        webSettings.setAllowFileAccess(true);// 设置允许访问文件数据
    }

    public static boolean isApplicationMaJia(Context context) {
        boolean flag = false;
        String apkType = UtilityBase.getAppMetedata(context,
                "APK_TYPE");
        int value = UtilityBase.parseInt(apkType);
        if (value > 1) {
            flag = true;
        }
        return flag;
    }

    public static int getMaJiaType(Context context) {
        String apkType = UtilityBase.getAppMetedata(context,
                "APK_TYPE");
        int value = UtilityBase.parseInt(apkType);
        return value;
    }

    /**
     * 下载其它动态so文件
     * test
     */
    public static void downloadSo(final Context context) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    String abi = Build.CPU_ABI;
                    String abi2 = Build.CPU_ABI2;
                    String cpuInfo = DeviceUtil.getCpuString();
                    String[] defaultCpuArray = context.getResources().getStringArray(R.array.array_main_cpu);
                    boolean flag = false;
                    for (int i = 0; i < defaultCpuArray.length; i++) {
                        String cpu = defaultCpuArray[i];
                        if (cpuInfo.contains(cpu)) {
                            flag = true;
                            break;
                        }
                    }

                    //当前有预置的abi
                    if (flag) {
                        return;
                    }

                    String libPath = "/data/data/" + context.getPackageName() + "/lib/";
                    File file = new File(libPath);
                    if (file.exists()) {
                        File[] files = file.listFiles();
                        int size = files.length;
                    }

//                    String downloadPath = SdLocal.getDownloadZipPath(context, "");
//                    HttpRequest.downloadFileBy("http://www.baidu.com", "", new CallBack() {
//                        @Override
//                        public void callBackSuccess(Object obj) {
//                            super.callBackSuccess(obj);
//                        }
//
//                        @Override
//                        public void callBackFail(Object obj) {
//                            super.callBackFail(obj);
//                        }
//                    });
                } catch (Exception e) {
                }
            }
        }).start();
    }

    public static void clearCookies(Context context) {
        // Edge case: an illegal state exception is thrown if an instance of
        // CookieSyncManager has not be created.  CookieSyncManager is normally
        // created by a WebKit view, but this might happen if you start the
        // app, restore saved state, and click logout before running a UI
        // dialog in a WebView -- in which case the app crashes

        try {
            @SuppressWarnings("unused")
            CookieSyncManager cookieSyncMngr =
                    CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.removeAllCookie();
        } catch (Exception e) {

        }
    }

    public static boolean checkAudioPermission() {
        boolean flag = true;
        try {
            int BUFFER_SIZE = AudioRecord.getMinBufferSize(8000,
                    AudioFormat.CHANNEL_IN_DEFAULT, AudioFormat.ENCODING_PCM_16BIT);
            AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                    8000, AudioFormat.CHANNEL_IN_DEFAULT,
                    AudioFormat.ENCODING_PCM_16BIT, BUFFER_SIZE);
            if (audioRecord != null) {
                audioRecord.startRecording();

                audioRecord.stop();
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    public static boolean checkListViewIsTop(ListView listView) {
        boolean result = false;
        if (listView.getFirstVisiblePosition() == 0) {
            final View topChildView = listView.getChildAt(0);
            result = topChildView.getTop() == 0;
        }
        return result;
    }

    public static boolean checkListViewIsBottom(ListView listView) {
        boolean result = false;
        try{
            if (listView != null && listView.getLastVisiblePosition() == (listView.getCount() - 1)) {
                final View bottomChildView = listView.getChildAt(listView.getLastVisiblePosition() - listView.getFirstVisiblePosition());
                if(bottomChildView != null)
                {
                    result = (listView.getHeight() >= bottomChildView.getBottom());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return result;
    }

    public static void firstUpload()
    {
        if(MyApplication.getInstance().mPushGetSuccessGeTui &&
                MyApplication.getInstance().mPushGetSuccessBaidu &&
                MyApplication.getInstance().mGetSuccessLocation)
        {
            MyApplication.getInstance().mPushGetSuccessGeTui = false;
            MyApplication.getInstance().mPushGetSuccessBaidu = false;
            MyApplication.getInstance().mGetSuccessLocation = false;
            LogUtilBase.LogD(null,"检查更新");
            // 检查更新
            BaseFragmentActivity currentActivity = (BaseFragmentActivity) AppManager.getAppManager().
                    currentActivity();
            UpdateManager.getInstance().checkUpdate(true, Setting.getAppStartUp(),
                    currentActivity, false, false);

            AppEnterTongJi.getInstance().requestEnterUse(currentActivity);
        }
    }

    public static void setShowSoftInputOnFocus(Activity activity,EditText editText)
    {
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        try {
            Class<EditText> cls = EditText.class;
            Method setSoftInputShownOnFocus;
            setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            setSoftInputShownOnFocus.setAccessible(true);
            setSoftInputShownOnFocus.invoke(editText, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setLayerTypeOff(View view)
    {
        //小于5.0
        if(Build.VERSION.SDK_INT < 21){
            if(view != null){
                view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            }
        }
    }
}
